import operator

from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils
import math
import re
import datetime
import operator


class KeywordCloudQuerier(ElasticSearchQuerier):

    def __init__(self, word_assoc_querier, nlp_service=None):
        super(KeywordCloudQuerier, self).__init__(None, None, None)
        self.word_assoc_querier = word_assoc_querier
        self.nlp_service = nlp_service

    def search(self, args):
        year = args.get('year')
        week = args.get('week')
        words = args.get('words')
        # ids_ = [word + year + week for word in words]

        res = {}
        ex_kw_dict = {}
        if words is not None:
            for word in words:
                try:
                    res = self.word_assoc_querier.search({"word": word, "year": year, "week": week})
                except Exception as e:
                    pass
                for k, w in zip(res.get('similar_words', []), res.get('similar_words_weight', [])):
                    ex_kw_dict[k] = ex_kw_dict.get(k, 0) + w

        ex_kw = sorted(ex_kw_dict.items(), key=operator.itemgetter(1), reverse=True)

        return {
            "ex_keywords": [x[0] for x in ex_kw],
            "ex_keywords_weight": [x[1] for x in ex_kw]
        }

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass

